package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.ProductBean;
import com.project.bean.SellInfoBean;
import com.project.bean.SellOrderBean;
import com.project.mapper.IProductMapper;
import com.project.mapper.ISellInfoMapper;
import com.project.mapper.ISellOrderMapper;
import com.project.service.ISellInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class SellInfoServiceImp implements ISellInfoService {
    @Autowired
    private ISellOrderMapper sellOrderMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public IPage<SellOrderBean> findByItem(Integer pageNO, String customerName, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<SellOrderBean> query = new QueryWrapper<>();
        if (customerName!= null && !customerName.equals("")) {
            query.like("so_customer", customerName);
        }
        if (startDate!= null ) {
            query.ge("so_date", startDate);
        }
        if (endDate!= null ) {
            query.le("so_date", endDate);
        }
        return sellOrderMapper.selectPage(new Page<>(pageNO, 3), query);
    }

    @Override
    public SellOrderBean findById(Integer sellOrderId) {
        SellOrderBean sellOrderBean = sellOrderMapper.selectById(sellOrderId);

        QueryWrapper<SellInfoBean> qw = new QueryWrapper<>();
        qw.eq("fk_sellOrderId",sellOrderId);
        List<SellInfoBean> list = sellInfoMapper.selectList(qw);
        for (SellInfoBean sellInfoBean : list) {
            ProductBean productBean = productMapper.selectById(sellInfoBean.getProductId());
            sellInfoBean.setProductBeanInSellInfo(productBean);
            sellInfoMapper.updateById(sellInfoBean);
        }

        sellOrderBean.setSellInfoBeanList(list);
        return sellOrderBean;
    }
}
